﻿using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using VideoSeller.Core.Configuration;
using VideoSeller.Core.Interfaces;

namespace VideoSeller.Business.Data
{
	public class Repository<T> where T : class
	{
		private readonly IApplicationSettingsProvider _applicationSettingsProvider;
		private VideoSellerDataContext _dataContext = null;

		protected VideoSellerDataContext DataContext
		{
            get
            {
                if (_dataContext == null)
                    _dataContext = new VideoSellerDataContext(_applicationSettingsProvider.VideoSellerConnectionString);
                
                return _dataContext;
            }
		}

		protected Table<T> Table
		{
			get { return DataContext.GetTable<T>(); }
		}

		protected Repository()
		{
			_applicationSettingsProvider = IoC.Resolve<IApplicationSettingsProvider>();
		}

		public IEnumerable<T> GetAll()
		{
			return Table.AsEnumerable();
		}

		protected T Insert(T entity)
		{
			Table.InsertOnSubmit(entity);
			SubmitAllChanges();
			return entity;
		}

		protected void Delete(T entity)
		{
			Table.DeleteOnSubmit(entity);
			SubmitAllChanges();
		}

		protected void SubmitAllChanges()
		{
			DataContext.SubmitChanges();
		}
	}
}